﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using CustomerManager.GUI.Code;
using System.Net.Mail;
using System.Threading;
using CustomerManager.GUI.Resources;
using System.Net;

namespace CustomerManager.GUI
{
    public partial class Main : Form
    {
        public Main()
        {
            InitializeComponent();
            notifyIcon1.Icon = CustomerManager.GUI.Properties.Resources.Icon1;
        }

        private void Main_Load(object sender, EventArgs e)
        {
            customersTableAdapter1.Fill(customers._Customers);
        }

        private void customersBindingNavigatorSaveItem_Click(object sender, EventArgs e)
        {
            if (Validate())
            {
                customersBindingSource.EndEdit();

                try
                {
                    tableAdapterManager1.UpdateAll(customers);
                }
                catch (Exception ex)
                {
                    MessageBox.Show(this, ex.Message, "Hiba!");
                }
            }
        }

        private void customersBindingNavigatorRefreshItem_Click(object sender, EventArgs e)
        {
            customers._Customers.Merge(customersTableAdapter1.GetData());
        }

        private void újCustomerToolStripMenuItem_Click(object sender, EventArgs e)
        {
            customersBindingSource.AddNew();
        }

        private void hírlevélKüldésToolStripMenuItem_Click(object sender, EventArgs e)
        {
            SendNews();
        }

        private void customersBindingNavigatorSendItem_Click(object sender, EventArgs e)
        {
            SendNews();
        }

        private void customersBindingNavigatorReportItem_Click(object sender, EventArgs e)
        {
            var f = new CustomerReport();
            f.SetDataSource(customersBindingSource);
            f.ShowDialog();
        }

        void SendNews()
        {
            if (backgroundWorker1.IsBusy)
            {
                MessageBox.Show(Strings.AlreadyInProgress);
                return;
            }

            List<String> emails = new List<string>();
            foreach (var row in this.customers._Customers)
            {
                emails.Add(row.Email);
            }

            if (emails.Count > 0)
            {
                var emailForm = new Email();
                var dr = emailForm.ShowDialog();

                if (dr == DialogResult.OK)
                {
                    backgroundWorker1.RunWorkerAsync(
                        new EmailState { 
                            Content = emailForm.Content, 
                            Subject = emailForm.Subject, 
                            Emails = emails });
                }
            }
            else
            {
                MessageBox.Show(Strings.NoItemToProcess);
                return;
            }
        }

        private void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e)
        {
            EmailState es = e.Argument as EmailState;
            if (es == null) throw new ArgumentNullException("EmailState");
            if (String.IsNullOrEmpty(es.Content)) throw new ArgumentNullException("Content");
            if (String.IsNullOrEmpty(es.Subject)) throw new ArgumentNullException("Subject");

            List<String> errors = new List<String>();
            if (es != null)
            {
                int i = 0;
                int c = es.Emails.Count;
                SmtpClient sc = new SmtpClient();
                if (sc.Port != 25) sc.EnableSsl = true;
                foreach (String email in es.Emails)
                {
                    i++;  
                    try
                    {
                        sc.Send("custo2000@gmail.com", email, es.Subject, es.Content);
                    }
                    catch (Exception ex)
                    {
                        errors.Add(ex.Message);
                    }

                    backgroundWorker1.ReportProgress(i * 100 / c);          
                }
            }

            e.Result = errors;
        }

        private void backgroundWorker1_ProgressChanged(object sender, ProgressChangedEventArgs e)
        {
            toolStripProgressBar1.Value = e.ProgressPercentage;
        }

        private void backgroundWorker1_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
        {
            toolStripProgressBar1.Value = 0;
            if (e.Error == null)
            {
                List<String> errors = e.Result as List<String>;
                if (errors.Count == 0)
                {
                    notifyIcon1.ShowBalloonTip(5000,
                        Strings.BallonNewsTitle,
                        Strings.BallonNewsSuccess,
                        ToolTipIcon.Info);
                }
                else
                {
                    notifyIcon1.ShowBalloonTip(5000,
                        Strings.BallonNewsTitle,
                        string.Format(Strings.BallonNewsSuccessWithErrors, errors.Count),
                        ToolTipIcon.Info);
                }
            }
            else
            {
                notifyIcon1.ShowBalloonTip(5000,
                    Strings.BallonNewsTitle,
                    string.Format(Strings.BallonNewsError, e.Error.Message),
                    ToolTipIcon.Error);
            }
        }

        private void Main_FormClosing(object sender, FormClosingEventArgs e)
        {
            if (backgroundWorker1.IsBusy)
            {
                e.Cancel = true;
                MessageBox.Show(Strings.AlreadyInProgress);
                return;
            }

            if (customers.HasChanges())
            {
                var dr = MessageBox.Show(
                    Strings.UnsavedItems, 
                    Strings.AreYouClose, 
                    MessageBoxButtons.YesNo);
                e.Cancel = dr == DialogResult.No;
            }
        }
    }
}
